#!/usr/bin/env python3
# -*- coding:utf-8 -*-
#
# Copyright 2013 suliu.net
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
#codeby     道长且阻
#email      ydhcui@suliu.net/QQ664284092
#website    http://www.suliu.net

import sys
import os
import json
import traceback
import random
import threading
import re
import time
import base64
import util
try:
  import urllib as parse
  import urllib2 as request
except ImportError as e:
  #print(e)
  from urllib import parse,request

from models import Setting,Userai,Aikey,Joke,Quotes,Qusers
sys.path.append(util.getpath("App"))

from App import kuaidi
from App.qzone import QZONE


class Core(object):
    cmdlist={}
    sep = " " #分隔符
    head= "#"
    hep = "?"
    qzones=[]
    link = re.compile(r"(http[s]?://(?:[-a-zA-Z0-9_]+\.)+[a-zA-Z]+(?::\d+)"
                       "?(?:/[-a-zA-Z0-9_%./]+)*\??[-a-zA-Z0-9_&%=.]*)",
                       re.UNICODE)

    def __init__(self,username):
        self.username=username
        self.sysfun = Sysfun()
        self.conf = Setting.get(Setting.username==username)
        self.qzone=QZONE(self.conf.username,self.conf.password)
        self.qzones.append(self.qzone)
        #for u,p in [(d.username,d.password) for d in Qusers.select()]:
             #self.qzones.append(QZONE(u,p))
             #pass

    def auto(self,instr,id=None):
        if not instr:return
        instr=instr.strip()
        if instr[:4]=='#>>>': #pyshell
            return self.sysfun.pyshell(instr[4:])
        try:
            cmdargs  = instr.split(self.sep)
            cmd,args = ''.join(cmdargs[:1]),cmdargs[1:]
            for cmds in self.cmdlist:
                if cmd==cmds:
                   if args:
                      if args[0]==self.hep:
                         return self.cmdlist[cmd].__doc__
                   return self.cmdlist[cmd](self,id,*args)
            urllink = self.link.search(instr)
            key = self.sysfun.admin['key']
            if urllink:
                return self.sysfun.gettitle(urllink.group(1))
            else:
                if self.sysfun.conf['chatmode'] or instr[:len(self.head)]==self.head:
                    return self.sysfun.chat(instr.replace(self.head,''))
        except Exception as e:
            if self.sysfun.conf["debug"]:
                type,value,tb = sys.exc_info()
                return '\n'.join(set(traceback.format_exception(type,value,tb)))
            else:
                return e
    @classmethod
    def regcmd(self,cmd):
        """注册命令 将命令与相应事件绑定"""
        def F(f):
            self.cmdlist.update({cmd:f})
            return f
        return F

    @classmethod
    def loadfun(self,code='UTF-8'):
        with open('userfun.py','r',encoding=code) as f:
            s = f.read()
            f.close()
        try:s=s.decode('GBK').encode('UTF-8')
        except:s=s
        exec(s)

class AI(object):
    def __init__(self):
        self.keylist = [d.data for d in Aikey.select()]
        self.Quotes_count_list=range(Quotes.select().count())

    def chat(self,inmsg):
        k=1
        try:
            msg=self.netbox(inmsg)
            if self.keyp(msg):
               msg=self.hito(msg)
               k=0
            if k:
                try:
                    Userai.get(Userai.instr==inmsg,Userai.outstr==msg)
                except Userai.DoesNotExist:
                    Userai.create(instr=inmsg,outstr=msg)#学习
        except:
            msg = "你可以发送 '#帮助' 给我查看更多信息。"

        relist = [d.outstr for d in Userai.select().where(Userai.instr==inmsg)]
        if relist:
            return random.choice(relist)
        return msg

    def keyp(self,value):
        if not value:return 1
        for key in self.keylist:
            sg = re.compile(key.strip(),re.UNICODE).search(value)
            if sg:
                return sg.group()

    def hito(self,msg=None):
        try:
            return Quotes.get(Quotes.id==random.choice(self.Quotes_count_list)).data
        except:
            url="http://api.hitokoto.us/rand"
            data=json.loads(util.get(url))
            return data["hitokoto"]

    def netbox(self,msg):
        try:
            headers={
                "Referer":"http://wendacloud.com/openapi/cloud/proexp.jsp",
                "Cookie":"JSESSIONID=aaaZO-c9T6vaY8MYiMoHu; CNZZDATA1000214860=1280602569-1409921308-http%253A%252F%252Fwww.tuicool.com%252F%7C1410067893"
            }
            url="http://wendacloud.com/openapi/productexp.do"
            data={"info":msg}
            """
            <xml>
            <ToUserName><![CDATA[110.87.113.6~aaaZO-c9T6vaY8MYiMoHu]]></ToUserName>
            <FromUserName><![CDATA[toUser]]></FromUserName>
            <CreateTime>1410068249613</CreateTime>
            <MsgType><![CDATA[text]]></MsgType>
            <Content><![CDATA[无奇不有属于成语，意思是什么奇怪的事物都有。]]></Content>
            <FuncFlag>0</FuncFlag>
            </xml>
            """
            res = util.post(url,data,headers)
            print(res,'netbox')
            result = util.find(res,'<Content><![CDATA[',']]></Content>')
        except:
            result = '连接超时'
        return result

    @classmethod
    def student(self,q,a):
        if q and a:
            Userai.create(instr=q,outstr=a)
            return "我学会啦！快来问我吧~"

class Sysfun(object):

    def __init__(self):
        self.ai=AI()
        self.conf ={
            'chatmode':0,  #是否启用聊天模式
            'debug':0,     #是否启用调试模式
        }
        self.admin={
            'key':'$$$#',
        }

    def chat(self,value):
        """自动聊天 eg:#chat 你好 """
        return self.ai.chat(value)

    def gettitle(self,url):
        """获取网页标题"""
        tre = re.compile(b'<title[^>]*>([^<]*)<')
        content = b''
        title = b''
        try:
            with request.urlopen(url) as r:
                for i in range(300):
                    content += r.read(64)
                    if len(content) < 64:
                        break
                    m = tre.search(content, re.IGNORECASE)
                    n = re.compile('<meta\s+http-equiv="?content-type"?'
                                   '\s+content="?[^;]+;\s*charset=([^">]+'
                                   ')"?\s*/?>|<meta\s+charset="?([^">/"]+'
                                   ')"?\s*/?>', re.IGNORECASE)  #有些SB网站把charset写在后面
                    if m and n:
                        title = m.group(1)
                        break
        except Exception as e:
            return "出错了:%s"%e
        if content.upper().find(b'UTF-8') != -1:
            charset = 'utf-8'
        elif content.upper().find(b'GB2312') != -1 or content.upper().find(b'GBK'):
            charset = 'gbk'
        elif content.upper().find(b'BIG5') != -1:
            charset = 'big5'
        else:
            charset= 'utf-8'
        try:
            title = title.decode(charset).replace('\n', '')
            title = title.strip()
        except UnboundLocalError: #G.F.W
            title = 'G.F.W我恨你'
        return "网页标题:%s"%title if title else '特么的什么玩意竟然找不到标题'

    #@Core.regcmd("#>>>")
    def pyshell(self,code):
        """执行py2代码 EG:#>>>print 's'*3 """
        url = "http://www.pythontip.com/coding/ajax_run"
        data= {'process':code}
        header={'Referer':'http://www.pythontip.com/coding/run'}
        res = util.post(url,data,header)
        return res



if __name__=='__main__':
    if not os.path.exists(util.getpath('res')):
        os.mkdir(util.getpath('res'))

    c=Core('664284092')
    #input()
    c.loadfun()
    '''
    while(1):
        try:
            print(c.auto(input("==>>"),'664284092'))
        except Exception as e:
            print(e)'''

    def addmsbg():
        for v in range(100):
            try:
                print(c.auto("#留言 819035877 %s"%c.sysfun.ai.hito(),'664284092'))
            except Exception as e:
                print(e)
            time.sleep(5)

    addmsbg()
